<template>
  <div class="app-container">
      <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:cost:add']"
        >新增</el-button>
      </el-col>
 </el-row>
   <div class="layoutStyle">
    <div class="leftStyle">
<el-table v-loading="loading" :data="costList"  show-summary  :summary-method="getSummaries" :header-cell-style="{textAlign: 'left' }">
   <el-table-column label="序号" prop="id" width="55" ></el-table-column>
    <el-table-column label="项次Item">
      <template #default="{ row }">
        <el-input v-model="row.item" v-if="row.isEditing" size="small"></el-input>
        <span v-else>{{ row.item }}</span>
      </template>
    </el-table-column>
    <el-table-column label="费率RMB/H"  prop="usageValue">
     <template #default="{ row }">
        <el-input v-model="row.usageValue" v-if="row.isEditing" size="small"></el-input>
        <span v-else>{{ row.usageValue }}</span>
      </template>
      </el-table-column>
      <el-table-column label="耗时/用量/次数"  prop="timeUsageNumber">
      <template #default="{ row }">
        <el-input v-model="row.timeUsageNumber" v-if="row.isEditing" size="small"></el-input>
        <span v-else>{{ row.timeUsageNumber }}</span>
      </template>
     </el-table-column>
      <el-table-column label="产品设计工时费用RMB"  prop="lineCost">
      <!-- <template #default="{ row }">
      {{ Number(row.usageValue?? 0)*Number(row.timeUsageNumber?? 0) }}
      </template> -->
     </el-table-column>
  
      <el-table-column label="操作"  class-name="small-padding fixed-width">
       <template #default="{ row, $index }">
        <el-button 
          v-if="!row.isEditing" 
          link 
          type="primary" 
          icon="Edit"
          @click="startEdit($index)"
          >编辑</el-button>
        
        <el-button 
          v-else 
          size="small" 
          type="success" 
          @click="saveEdit($index)"
          style="width: 50px"
        >保存</el-button>
        
        <el-button 
          v-if="row.isEditing" 
          size="small" 
          type="primary"
          @click="cancelEdit($index)"
          style="width: 50px"
        >取消</el-button>
        
        <el-button 
          v-if="!row.isEditing" 
         link 
          type="primary" 
          icon="Delete"
          @click="deleteRow(row)"
        >删除</el-button>
      </template>




        <!-- <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:cost:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:cost:remove']">删除</el-button>
        </template> -->

  <!-- <template #default="{ row }">
        <el-button type="primary" link @click="resetData(row)">
          保存
        </el-button>
      </template> -->



      </el-table-column>
    </el-table>
    
<!-- 添加或修改设计成本对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="costRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="项次Item" prop="item">
          <el-input v-model="form.item" placeholder="请输入项次Item" />
        </el-form-item>
        <el-form-item label="费率RMB/H" prop="usageValue">
          <el-input v-model="form.usageValue" placeholder="请输入费率RMB/H" />
        </el-form-item>
       <el-form-item label="耗时/用量/次数" prop="timeUsageNumber">
          <el-input v-model="form.timeUsageNumber" placeholder="耗时/用量/次数" />
        </el-form-item>
        <el-form-item label="产品设计工时费用RMB" prop="lineCost">
          <el-input v-model="form.lineCost" placeholder="请输入产品设计工时费用RMB" />
        </el-form-item>
        <!-- <el-form-item label="产品设计工时费用合计RMB" prop="totalCost">
          <el-input v-model="form.totalCost" placeholder="请输入产品设计工时费用合计RMB" />
        </el-form-item> -->
        <el-form-item label="零件ID" prop="pid">
          <el-input v-model="form.pid" placeholder="请输入零件ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
       </div>
    <div class="rightStyle">
      
    </div>
    </div>
  </div>
</template>

<script setup name="Cost">
import { listCost, getCost, delCost, addCost, updateCost } from "@/api/system/cost"
import EditableCell from '@/components/EditableCell/EditableCell.vue'
const { proxy } = getCurrentInstance()
const emit = defineEmits(['changeVal'])
const costList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pid: null,
  },
  rules: {
    item: [
      { required: true, message: "项次Item不能为空", trigger: "blur" }
    ],
    usageValue: [
      { required: true, message: "费率RMB/H不能为空", trigger: "blur" }
    ],
    lineCost: [
      { required: true, message: "产品设计工时费用RMB不能为空", trigger: "blur" }
    ],
    totalCost: [
      { required: true, message: "产品设计工时费用合计RMB不能为空", trigger: "blur" }
    ],
    pid: [
      { required: true, message: "零件ID不能为空", trigger: "blur" }
    ],
    ptype: [
      { required: true, message: "零件类型ID不能为空", trigger: "change" }
    ],
  }
})

// Define which columns to sum (by prop name)
const sumColumns = ['lineCost']

const getSummaries = ({ columns, data }) => {
  const sums = []
  
  columns.forEach((column, index) => {
    // First column: show "合计"
    if (index === 0) {
      sums[index] = '合计'
      return
    }

    // Check if this column should be summed
    if (sumColumns.includes(column.property)) {
      const values = data.map(item => Number(item[column.property]))
      
      // Only sum if all values are valid numbers
      if (!values.every(value => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr)
          return !isNaN(value) ? prev + curr : prev
        }, 0)
        
        // Format with currency for price/total
        if (column.property === 'price' || column.property === 'total') {
          sums[index] = `¥${sum.toFixed(2)}`
        } else {
          sums[index] = sum
        }
      } else {
        sums[index] = ''
      }
    } else {
      // Non-summed columns: show dash
      sums[index] = ''
    }
  })
  emit('changeVal',sums[4])
  return sums
}

const { queryParams, form, rules } = toRefs(data)
// const tableData = ref([/* 数据 */])
const originalData = ref([]) // 用于存储原始数据，用于取消操作

const startEdit = (index) => {
  // 保存原始数据
  originalData.value[index] = { ...costList.value[index] }
  costList.value[index].isEditing = true
}

const saveEdit = (index) => {
  costList.value[index].isEditing = false
  // 这里调用API保存数据
  costList.value[index].lineCost = costList.value[index].usageValue*costList.value[index].timeUsageNumber
         updateCost(costList.value[index]).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })

}

const cancelEdit = (index) => {
  // 恢复原始数据
  costList.value[index] = { ...originalData.value[index] }
  costList.value[index].isEditing = false
}

/** 查询设计成本列表 */
function getList() {
  loading.value = true
  listCost(queryParams.value).then(response => {
    costList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    item: null,
    usageValue: null,
    lineCost: null,
    totalCost: null,
    pid: null,
    ptype: null,
    uid: null,
    updateDate: null,
    createDate: null,
    deleteDate: null
  }
  proxy.resetForm("costRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设计成本"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCost(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改设计成本"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["costRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCost(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        form.value.lineCost = form.value.usageValue*form.value.timeUsageNumber
        addCost(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除设计成本编号为"' + _ids + '"的数据项？').then(function() {
    return delCost(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/cost/export', {
    ...queryParams.value
  }, `cost_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.layoutStyle{
  display: flex;
  flex-direction: row;
  .leftStyle{
    width: 65%;
   }
  .rightStyle{
    width: 35%;
  }
  ul, ol {
  list-style-type: none; /* 移除所有列表的默认标记 */
  padding-left: 0; /* 移除默认的左缩进 */
  margin-left: 0;
  }
  ol {
    height: 140px;
  }
}

</style>